#pragma execution_character_set("utf-8")
#include "task_view_model.h"
#include <QDateTime>
#include <algorithm>

namespace presentation {
namespace viewmodels {

// ==================== TaskListModel ====================

TaskListModel::TaskListModel(QObject* parent)
    : QAbstractListModel(parent)
{
}

int TaskListModel::rowCount(const QModelIndex& parent) const
{
    Q_UNUSED(parent);
    return static_cast<int>(m_taskList.size());
}

QVariant TaskListModel::data(const QModelIndex& index, int role) const
{
    if (!index.isValid() || index.row() >= static_cast<int>(m_taskList.size())) {
        return QVariant();
    }

    const auto& task = m_taskList[index.row()];

    switch (role) {
    case ChainIdRole:           return task.chainId;
    case TaskNameRole:          return task.taskName;
    case AgvNumberRole:         return task.agvNumber;
    case AgvNameRole:           return task.agvName;
    case StatusRole:            return task.status;
    case StatusDisplayRole:     return task.statusDisplay;
    case CurrentTaskIndexRole:  return task.currentTaskIndex;
    case TotalTasksRole:        return task.totalTasks;
    case ProgressRole:          return task.progress;
    case CreateTimeRole:        return task.createTime;
    case ErrorMessageRole:      return task.errorMessage;
    case CurrentSubTaskRole:    return task.currentSubTask;
    case CurrentSubTaskTypeRole: return task.currentSubTaskType;
    case TargetStationRole:     return task.targetStation;
    case CurrentFloorRole:      return task.currentFloor;
    case DurationSecondsRole:   return task.durationSeconds;
    case IsPausedRole:          return task.isPaused;
    case IsFinishedRole:        return task.isFinished;
    default:
        return QVariant();
    }
}

QHash<int, QByteArray> TaskListModel::roleNames() const
{
    QHash<int, QByteArray> roles;
    roles[ChainIdRole] = "chainId";
    roles[TaskNameRole] = "taskName";
    roles[AgvNumberRole] = "agvNumber";
    roles[AgvNameRole] = "agvName";
    roles[StatusRole] = "status";
    roles[StatusDisplayRole] = "statusDisplay";
    roles[CurrentTaskIndexRole] = "currentTaskIndex";
    roles[TotalTasksRole] = "totalTasks";
    roles[ProgressRole] = "progress";
    roles[CreateTimeRole] = "createTime";
    roles[ErrorMessageRole] = "errorMessage";
    roles[CurrentSubTaskRole] = "currentSubTask";
    roles[CurrentSubTaskTypeRole] = "currentSubTaskType";
    roles[TargetStationRole] = "targetStation";
    roles[CurrentFloorRole] = "currentFloor";
    roles[DurationSecondsRole] = "durationSeconds";
    roles[IsPausedRole] = "isPaused";
    roles[IsFinishedRole] = "isFinished";
    return roles;
}

QVariantMap TaskListModel::getTaskData(int row) const
{
    QVariantMap result;
    if (row < 0 || row >= static_cast<int>(m_taskList.size())) {
        return result;
    }

    const auto& task = m_taskList[row];
    result["chainId"] = task.chainId;
    result["taskName"] = task.taskName;
    result["agvNumber"] = task.agvNumber;
    result["agvName"] = task.agvName;
    result["status"] = task.status;
    result["statusDisplay"] = task.statusDisplay;
    result["currentTaskIndex"] = task.currentTaskIndex;
    result["totalTasks"] = task.totalTasks;
    result["progress"] = task.progress;
    result["createTime"] = task.createTime;
    result["errorMessage"] = task.errorMessage;
    result["currentSubTask"] = task.currentSubTask;
    result["currentSubTaskType"] = task.currentSubTaskType;
    result["targetStation"] = task.targetStation;
    result["currentFloor"] = task.currentFloor;
    result["durationSeconds"] = task.durationSeconds;
    result["isPaused"] = task.isPaused;
    result["isFinished"] = task.isFinished;

    return result;
}

void TaskListModel::updateData(const std::vector<TaskListItem>& taskList)
{
    beginResetModel();
    m_taskList = taskList;
    endResetModel();
}

void TaskListModel::updateTask(const QString& chainId, const TaskListItem& task)
{
    for (size_t i = 0; i < m_taskList.size(); ++i) {
        if (m_taskList[i].chainId == chainId) {
            m_taskList[i] = task;
            auto index = createIndex(static_cast<int>(i), 0);
            emit dataChanged(index, index);
            return;
        }
    }

    // 如果不存在，添加新任务
    beginInsertRows(QModelIndex(), static_cast<int>(m_taskList.size()), static_cast<int>(m_taskList.size()));
    m_taskList.push_back(task);
    endInsertRows();
}

void TaskListModel::removeTask(const QString& chainId)
{
    for (size_t i = 0; i < m_taskList.size(); ++i) {
        if (m_taskList[i].chainId == chainId) {
            beginRemoveRows(QModelIndex(), static_cast<int>(i), static_cast<int>(i));
            m_taskList.erase(m_taskList.begin() + i);
            endRemoveRows();
            return;
        }
    }
}

// ==================== TaskViewModel ====================

TaskViewModel::TaskViewModel(
    std::shared_ptr<application::task::TaskService> taskService,
    QObject* parent)
    : BaseViewModel(parent)
    , m_taskService(taskService)
    , m_taskListModel(std::make_unique<TaskListModel>(this))
{
    if (!m_taskService) {
        qWarning() << "TaskViewModel: TaskService is null!";
        return;
    }

    m_taskService->setPlanningFailureNotifier([this](const QString& message) {
        emit errorOccurred(message);
    });

    // 连接 TaskExecutor 信号
    auto* executor = m_taskService->getExecutor();
    if (executor) {
        connect(executor, &application::task::TaskExecutor::taskChainCompleted,
                this, &TaskViewModel::onTaskChainCompleted);
        connect(executor, &application::task::TaskExecutor::taskChainProgressUpdated,
                this, &TaskViewModel::onTaskChainProgressUpdated);
        connect(executor, &application::task::TaskExecutor::taskChainStatusUpdated,
                this, &TaskViewModel::onTaskChainStatusUpdated);
        connect(executor, &application::task::TaskExecutor::taskChainAdded,
                this, &TaskViewModel::onTaskChainAdded);
        connect(executor, &application::task::TaskExecutor::taskChainRemoved,
                this, &TaskViewModel::onTaskChainRemoved);
    }

    // 加载可用模板
    loadAvailableTemplates();

    // 初始刷新任务列表
    refreshTasks();
}

TaskViewModel::TaskViewModel(
    application::task::TaskService* taskService,
    QObject* parent)
    : BaseViewModel(parent)
    , m_taskService(taskService, [](application::task::TaskService*){}) // 非拥有的 shared_ptr
    , m_taskListModel(std::make_unique<TaskListModel>(this))
{
    if (!m_taskService) {
        qWarning() << "TaskViewModel: TaskService is null!";
        return;
    }

    m_taskService->setPlanningFailureNotifier([this](const QString& message) {
        emit errorOccurred(message);
    });

    // 连接 TaskExecutor 信号
    auto* executor = m_taskService->getExecutor();
    if (executor) {
        connect(executor, &application::task::TaskExecutor::taskChainCompleted,
                this, &TaskViewModel::onTaskChainCompleted);
        connect(executor, &application::task::TaskExecutor::taskChainProgressUpdated,
                this, &TaskViewModel::onTaskChainProgressUpdated);
        connect(executor, &application::task::TaskExecutor::taskChainStatusUpdated,
                this, &TaskViewModel::onTaskChainStatusUpdated);
        connect(executor, &application::task::TaskExecutor::taskChainAdded,
                this, &TaskViewModel::onTaskChainAdded);
        connect(executor, &application::task::TaskExecutor::taskChainRemoved,
                this, &TaskViewModel::onTaskChainRemoved);
    }

    // 加载可用模板
    loadAvailableTemplates();

    // 初始刷新任务列表
    refreshTasks();
}

QString TaskViewModel::createTaskFromTemplate(const QString& templateName, int agvNumber)
{
    if (!m_taskService) {
        emit errorOccurred(tr("任务服务不可用"));
        return "";
    }

    auto result = m_taskService->createTaskFromTemplate(
        templateName.toStdString(),
        agvNumber
    );

    if (result.isSuccess()) {
        QString chainId = QString::fromStdString(result.getValue());
        emit taskCreated(chainId);
        refreshTasks();
        return chainId;
    } else {
        emit errorOccurred(result.getErrorMessage());
        return "";
    }
}

QString TaskViewModel::createMoveTask(const QString& targetStation, int floor, int agvNumber)
{
    if (!m_taskService) {
        emit errorOccurred(tr("任务服务不可用"));
        return "";
    }

    auto result = m_taskService->createMoveTask(
        targetStation.toStdString(),
        floor,
        agvNumber
    );

    if (result.isSuccess()) {
        QString chainId = QString::fromStdString(result.getValue());
        emit taskCreated(chainId);
        refreshTasks();
        return chainId;
    } else {
        emit errorOccurred(result.getErrorMessage());
        return "";
    }
}

QString TaskViewModel::createChargeTask(int agvNumber, const QString& chargePoint, int targetBatteryLevel)
{
    if (!m_taskService) {
        emit errorOccurred(tr("任务服务不可用"));
        return "";
    }

    auto result = m_taskService->createChargeTask(
        agvNumber,
        chargePoint.toStdString(),
        targetBatteryLevel
    );

    if (result.isSuccess()) {
        QString chainId = QString::fromStdString(result.getValue());
        emit taskCreated(chainId);
        refreshTasks();
        return chainId;
    } else {
        emit errorOccurred(result.getErrorMessage());
        return "";
    }
}

QString TaskViewModel::createParkTask(int agvNumber, const QString& parkingStation)
{
    if (!m_taskService) {
        emit errorOccurred(tr("任务服务不可用"));
        return "";
    }

    auto result = m_taskService->createParkTask(
        agvNumber,
        parkingStation.toStdString()
    );

    if (result.isSuccess()) {
        QString chainId = QString::fromStdString(result.getValue());
        emit taskCreated(chainId);
        refreshTasks();
        return chainId;
    } else {
        emit errorOccurred(result.getErrorMessage());
        return "";
    }
}

bool TaskViewModel::pauseTask(const QString& chainId)
{
    if (!m_taskService) {
        return false;
    }

    auto result = m_taskService->pauseTask(chainId.toStdString());
    if (result.isSuccess()) {
        refreshTasks();
        return true;
    } else {
        emit errorOccurred(result.getErrorMessage());
        return false;
    }
}

bool TaskViewModel::resumeTask(const QString& chainId)
{
    if (!m_taskService) {
        return false;
    }

    auto result = m_taskService->resumeTask(chainId.toStdString());
    if (result.isSuccess()) {
        refreshTasks();
        return true;
    } else {
        emit errorOccurred(result.getErrorMessage());
        return false;
    }
}

bool TaskViewModel::cancelTask(const QString& chainId)
{
    if (!m_taskService) {
        return false;
    }

    auto result = m_taskService->cancelTask(chainId.toStdString());
    if (result.isSuccess()) {
        refreshTasks();
        return true;
    } else {
        emit errorOccurred(result.getErrorMessage());
        return false;
    }
}

bool TaskViewModel::rescheduleAgv(int agvNumber)
{
    if (!m_taskService) {
        emit errorOccurred(tr("任务服务不可用"));
        return false;
    }
    if (agvNumber < 0) {
        emit errorOccurred(tr("无效的AGV编号"));
        return false;
    }
    bool ok = m_taskService->rescheduleAgvTask(agvNumber);
    if (!ok) {
        emit errorOccurred(tr("重新调度失败或AGV不可用"));
    }
    return ok;
}

bool TaskViewModel::resetCurrentSubTask(const QString& chainId)
{
    if (!m_taskService) {
        return false;
    }

    auto result = m_taskService->resetCurrentSubTask(chainId.toStdString());
    if (!result.isSuccess()) {
        emit errorOccurred(result.getErrorMessage());
        return false;
    }
    return true;
}

void TaskViewModel::refreshTasks()
{
    // 手动全量同步接口：从 TaskExecutor 重新加载所有任务链
    // 用途：
    // 1. 初始化时加载现有任务
    // 2. 手动刷新按钮的兜底方案
    // 3. 调试和恢复场景
    //
    // 注意：日常使用应依赖事件驱动（taskChainAdded/Removed/Progress/Status信号）
    // 而非频繁调用此方法

    if (!m_taskService) {
        return;
    }

    // 获取所有活跃任务链ID
    auto chainIds = m_taskService->getActiveTaskIds();

    std::vector<TaskListItem> taskList;
    taskList.reserve(chainIds.size());

    // 为每个任务链创建列表项
    for (const auto& chainId : chainIds) {
        auto* state = m_taskService->getTaskState(chainId);
        if (state) {
            taskList.push_back(createTaskListItem(state));
        }
    }

    // 更新模型
    m_taskListModel->updateData(taskList);

    // 更新缓存
    m_taskCache.clear();
    for (const auto& item : taskList) {
        m_taskCache[item.chainId] = item;
    }

    // 更新统计
    updateStatistics();
}

bool TaskViewModel::reloadTaskConfig()
{
    if (!m_taskService) {
        return false;
    }

    auto result = m_taskService->reloadTaskConfig();
    if (result.isSuccess()) {
        loadAvailableTemplates();
        return true;
    } else {
        emit errorOccurred(result.getErrorMessage());
        return false;
    }
}

QVariantMap TaskViewModel::getTaskDetails(const QString& chainId)
{
    QVariantMap result;

    if (!m_taskService) {
        return result;
    }

    auto* state = m_taskService->getTaskState(chainId.toStdString());
    if (!state) {
        return result;
    }

    result["chainId"] = QString::fromStdString(state->chainId);
    result["id"] = result["chainId"];
    result["taskName"] = QString::fromStdString(state->taskName);
    result["agvNumber"] = state->agvNumber;
    result["agvName"] = getAgvName(state->agvNumber);
    result["status"] = formatTaskStatus(state);
    result["statusDisplay"] = result["status"];
    result["currentTaskIndex"] = static_cast<int>(state->currentTaskIndex);
    result["totalTasks"] = static_cast<int>(state->tasks.size());
    result["paused"] = state->paused;
    result["finished"] = state->finished;
    result["errorMessage"] = QString::fromStdString(state->context.errorMessage);
    result["assignedAgv"] = result["agvName"];
    result["priority"] = 0;

    // 计算进度
    int progress = 0;
    if (!state->tasks.empty()) {
        progress = static_cast<int>((state->currentTaskIndex * 100) / state->tasks.size());
    }
    result["progress"] = progress;

    QString currentSubTaskName;
    QString currentSubTaskType;
    int currentStageValue = -1;
    if (!state->tasks.empty() && state->currentTaskIndex < state->tasks.size()) {
        const auto* currentTask = state->tasks[state->currentTaskIndex].get();
        if (currentTask) {
            currentSubTaskName = QString::fromStdString(currentTask->getDescription());
            currentSubTaskType = QString::fromStdString(kernel::task::taskTypeToString(currentTask->getType()));
            currentStageValue = static_cast<int>(currentTask->getStage());
        }
    }

    result["currentSubTask"] = currentSubTaskName;
    result["currentSubTaskType"] = currentSubTaskType;
    result["currentSubTaskStage"] = currentStageValue;

    const auto createMs = std::chrono::duration_cast<std::chrono::milliseconds>(
        state->createTime.time_since_epoch()).count();
    result["createTime"] = static_cast<qint64>(createMs);

    const auto now = std::chrono::system_clock::now();
    const auto durationSec = std::chrono::duration_cast<std::chrono::seconds>(
        now - state->createTime).count();
    result["durationSeconds"] = static_cast<qint64>(std::max<int64_t>(0, durationSec));

    return result;
}

void TaskViewModel::onTaskChainCompleted(const QString& chainId, bool success)
{
    emit taskCompleted(chainId, success);
    refreshTasks();
}

void TaskViewModel::onTaskChainProgressUpdated(const QString& chainId, int current, int total)
{
    emit taskProgressUpdated(chainId, current, total);

    // 更新缓存中的任务
    if (m_taskCache.contains(chainId)) {
        auto& item = m_taskCache[chainId];
        item.currentTaskIndex = current;
        item.totalTasks = total;
        if (total > 0) {
            item.progress = (current * 100) / total;
        }
        m_taskListModel->updateTask(chainId, item);
    }
}

void TaskViewModel::onTaskChainStatusUpdated(const QString& chainId, const QString& status)
{
    emit taskStatusUpdated(chainId, status);

    // 更新缓存中的任务
    if (m_taskCache.contains(chainId)) {
        auto& item = m_taskCache[chainId];
        item.statusDisplay = status;
        m_taskListModel->updateTask(chainId, item);
    }
}

void TaskViewModel::onTaskChainAdded(const QString& chainId, int agvNumber, const QString& taskName)
{
    // 当任务链添加时，立即获取其状态并更新到缓存和模型中
    // 这样任何来源创建的任务（QML、呼叫器、自动充电等）都能即时显示

    auto* executor = m_taskService->getExecutor();
    if (!executor) {
        return;
    }

    // 获取任务链的完整状态
    auto state = executor->getTaskChainState(chainId.toStdString());
    if (!state) {
        return;
    }

    // 创建任务列表项
    TaskListItem item = createTaskListItem(state);

    // 添加到缓存
    m_taskCache[chainId] = item;

    // 更新到列表模型（会触发 QML 界面更新）
    m_taskListModel->updateTask(chainId, item);

    // 更新统计数据
    updateStatistics();

    // 发射任务创建信号给 QML
    emit taskCreated(chainId);
}

void TaskViewModel::onTaskChainRemoved(const QString& chainId)
{
    // 当任务链从 Executor 中移除时，同步清理缓存和模型
    // 这样界面可以即时反映任务队列的变化

    if (!m_taskCache.contains(chainId)) {
        return;
    }

    // 从缓存中移除
    m_taskCache.remove(chainId);

    // 从列表模型中移除（会触发 QML 界面更新）
    m_taskListModel->removeTask(chainId);

    // 更新统计数据
    updateStatistics();
}

void TaskViewModel::updateTaskList()
{
    refreshTasks();
}

void TaskViewModel::updateStatistics()
{
    int total = static_cast<int>(m_taskCache.size());
    int active = 0;
    int completed = 0;
    int failed = 0;

    for (const auto& item : m_taskCache) {
        if (item.status == "executing" ||
            item.status == "pending" ||
            item.status == "timeout") {
            active++;
        } else if (item.status == "completed") {
            completed++;
        } else if (item.status == "failed") {
            failed++;
        }
    }

    if (m_totalTaskCount != total) {
        m_totalTaskCount = total;
        emit totalTaskCountChanged();
    }

    if (m_activeTaskCount != active) {
        m_activeTaskCount = active;
        emit activeTaskCountChanged();
    }

    if (m_completedTaskCount != completed) {
        m_completedTaskCount = completed;
        emit completedTaskCountChanged();
    }

    if (m_failedTaskCount != failed) {
        m_failedTaskCount = failed;
        emit failedTaskCountChanged();
    }
}

void TaskViewModel::loadAvailableTemplates()
{
    if (!m_taskService) {
        return;
    }

    auto templates = m_taskService->getAvailableTemplates();

    QStringList templateList;
    for (const auto& tmpl : templates) {
        templateList.append(QString::fromStdString(tmpl));
    }

    if (m_availableTemplates != templateList) {
        m_availableTemplates = templateList;
        emit availableTemplatesChanged();
    }
}

TaskListItem TaskViewModel::createTaskListItem(const application::task::TaskChainState* state)
{
    TaskListItem item;

    item.chainId = QString::fromStdString(state->chainId);
    item.taskName = QString::fromStdString(state->taskName);
    item.agvNumber = state->agvNumber;
    item.agvName = getAgvName(state->agvNumber);
    item.status = formatTaskStatus(state);
    item.statusDisplay = item.status;
    item.currentTaskIndex = static_cast<int>(state->currentTaskIndex);
    item.totalTasks = static_cast<int>(state->tasks.size());
    item.isPaused = state->paused;
    item.isFinished = state->finished;

    // 计算进度
    if (state->tasks.size() > 0) {
        item.progress = (state->currentTaskIndex * 100) / state->tasks.size();
        if (item.isFinished) {
            item.progress = 100;
        }
    }

    // 获取当前子任务信息
    if (!state->tasks.empty() && state->currentTaskIndex < state->tasks.size()) {
        const auto* currentTask = state->tasks[state->currentTaskIndex].get();
        if (currentTask) {
            item.currentSubTask = QString::fromStdString(currentTask->getDescription());
            item.currentSubTaskType = QString::fromStdString(kernel::task::taskTypeToString(currentTask->getType()));

            // 尝试从子任务描述中提取目标站点信息
            QString desc = QString::fromStdString(currentTask->getDescription());
            item.currentSubTask = desc;
            if (item.targetStation.isEmpty()) {
                item.targetStation = desc;
            }
            item.currentFloor = 0;
        }
    }

    // 格式化创建时间
    auto timePoint = state->createTime;
    auto time_t = std::chrono::system_clock::to_time_t(timePoint);
    QDateTime dt = QDateTime::fromSecsSinceEpoch(time_t);
    item.createTime = dt.toString("yyyy-MM-dd hh:mm:ss");

    // 计算运行时长
    auto now = std::chrono::system_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::seconds>(now - state->createTime);
    item.durationSeconds = duration.count();

    item.errorMessage = QString::fromStdString(state->context.errorMessage);

    return item;
}

QString TaskViewModel::formatTaskStatus(const application::task::TaskChainState* state)
{
    if (state->finished) {
        if (state->context.hasError()) {
            return "failed";
        }
        return "completed";
    }

    if (state->paused) {
        return "paused";
    }

    switch (state->status) {
    case kernel::task::TaskChainStatus::Ok:
        return state->currentTaskIndex == 0 ? "pending" : "executing";
    case kernel::task::TaskChainStatus::KeepOn:
        return "executing";
    case kernel::task::TaskChainStatus::Suspend:
        return "suspended";
    case kernel::task::TaskChainStatus::Timeout:
        return "timeout";
    case kernel::task::TaskChainStatus::Error:
        return "error";
    case kernel::task::TaskChainStatus::Recalculation:
        return "recalculating";
    case kernel::task::TaskChainStatus::DispatcherMove:
        return "dispatching";
    default:
        return "unknown";
    }
}

QString TaskViewModel::getAgvName(int agvNumber)
{
    return QString("AGV-%1").arg(agvNumber, 3, 10, QChar('0'));
}

bool TaskViewModel::callerTriggerEnabled() const
{
    if (!m_taskService) {
        return false;
    }
    return m_taskService->isCallerTriggerEnabled();
}

void TaskViewModel::setCallerTriggerEnabled(bool enabled)
{
    if (!m_taskService) {
        return;
    }

    m_taskService->setCallerTriggerEnabled(enabled);
    emit callerTriggerEnabledChanged();
}

bool TaskViewModel::callerDuplicateCheckEnabled() const
{
    if (!m_taskService) {
        return true;
    }
    return m_taskService->isCallerDuplicateCheckEnabled();
}

void TaskViewModel::setCallerDuplicateCheckEnabled(bool enabled)
{
    if (!m_taskService) {
        return;
    }

    m_taskService->setCallerDuplicateCheckEnabled(enabled);
    emit callerDuplicateCheckEnabledChanged();
}

bool TaskViewModel::callerMutexCheckEnabled() const
{
    if (!m_taskService) {
        return true;
    }
    return m_taskService->isCallerMutexCheckEnabled();
}

void TaskViewModel::setCallerMutexCheckEnabled(bool enabled)
{
    if (!m_taskService) {
        return;
    }

    m_taskService->setCallerMutexCheckEnabled(enabled);
    emit callerMutexCheckEnabledChanged();
}

} // namespace viewmodels
} // namespace presentation
